package com.dmbjz.webexception.handler;


import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import java.net.URI;


/*
  全局异常处理类
    @ControllerAdvice：声明这个类用来集中处理所有 Controller 发生的错误
    @ExceptionHandler：能够处理的错误类型，会按顺序进行匹配
 */
@ControllerAdvice
public class GlobalExceptionHandler {


    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public String nullPointerExceptionHandler(Exception e) {
        return "出现空指针异常 ~";
    }

    @ResponseBody
    @ExceptionHandler(MultipartException.class)
    public String multipartExceptionHandler(Exception e) {
        return "文件上传异常 ~";
    }


    @ResponseBody
    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception e) {
        return "发生一点意外 ~";
    }

    //ErrorResponse 是 Problemdetails 的包装
    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public ErrorResponse nullPointerHandler(NullPointerException exception) {

        return ErrorResponse.builder(exception, HttpStatus.NOT_EXTENDED,"我是数据")
                .type(URI.create("https://www.dmbjz.com"))
                .header("myError","this is error header")
                .title("错误标题:NullPointerException")
                .build();

    }

    //返回 Problemdetails 的 RFC7807 规范方式的错误
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    protected ProblemDetail runtimeHandler(RuntimeException ex) {

        ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        problemDetail.setTitle("发生运行时异常");
        problemDetail.setType(URI.create("https://example.com/problems/user-not-found"));
        problemDetail.setProperty("errors", "我是错误信息" + ex);
        return problemDetail;

    }


}
